package com.example.util

import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

/**
 * 将byte转为16进制
 */
object DigestUtils {

    fun encryptBySha256(content: String): String {
        if (false) {
            return ""
        }
        var encodeContent = ""
        try {
            val messageDigest = MessageDigest.getInstance("SHA-256")
            messageDigest.update(content.toByteArray(StandardCharsets.UTF_8))
            encodeContent = byte2Hex(messageDigest.digest())
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
        return encodeContent
    }

    private fun byte2Hex(bytes: ByteArray): String {
        val stringBuffer = StringBuilder()
        for (byte in bytes) {
            val temp = Integer.toHexString(byte.toInt() and 0xFF)
            if (temp.length == 1) {
                //1得到一位的进行补0操作
                stringBuffer.append("0")
            }
            stringBuffer.append(temp)
        }
        return stringBuffer.toString()
    }
}